package server;




import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoSession;

import db.SimpleLogger;

/**
 * the class of ChatServiceHandler implements IoHandler 
 * and receive the client 
 * @author wangkaidi
 *
 */
public class ChatServiceHandler implements IoHandler
{	
	private SessionManager sm=SessionManager.getInstance();
	
	@Override
	public void exceptionCaught(IoSession session, Throwable arg1)throws Exception 
	{	
		int id=sm.getIdBySession(session);
		if(id<0)
		{
			SimpleLogger.getInstance().log(SimpleLogger.FATAL,"can not find session id");
		}
		else
		{
			sm.removeSession(id);//remove the session from the SessionManager
		}
	}

	@Override
	public void messageReceived(IoSession session, Object input) throws Exception
	{		
		ChatServiceProcessor.getInstance().process(session, input.toString());//process the input
	}

	@Override
	public void messageSent(IoSession arg0, Object arg1) throws Exception 
	{		
	}

	@Override
	public void sessionClosed(IoSession arg0) throws Exception 
	{	
		
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception
	{		
		int id=IdGenerator.getInstance().getNext();
		sm.addSession(id, session);//add a new session to SessionManager		
	}

	@Override
	public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception 
	{				
	}

	@Override
	public void sessionOpened(IoSession arg0) throws Exception
	{			
	}

}
